<?php
declare (strict_types = 1);

namespace app\index\model;

use think\Db;
use think\facade\Config;
use think\facade\Configphp;
use think\facade\Request;
use think\facade\View;
use think\Image;
use think\Model;
use think\model\concern\SoftDelete;

/**
 * @mixin \think\Model
 */
class Goods extends Model
{
    protected $pk = 'goods_id';
    use SoftDelete;
    protected $deleteTime = 'del';
    protected $error;
    //protected $readonly = ['goods_name'];

    public function getError(){
        return $this->error;
    }
    public function searchPriceMinAttr($query,$value,$data){
        if(""!==$value){
            $query->where('price','>=',$value);
        }
    }
    public function searchPriceMaxAttr($query,$value,$data){
        if(""!==$value){
            $query->where('price','<=',$value);
        }
    }
    public function searchGoodsNameAttr($query,$value,$data){
        if(""!==$value){
            $query->where('goods_name','like','%'.$value.'%');
        }
    }
    public function searchCateIdAttr($query,$value,$data){
        if (""!==$value){
            $query->where(function ($q)use ($value){
                $q->where('c.cate_id','=',$value);
            });
        }
    }
    public function searchAddTimeMinAttr($query,$value,$data){
        if(!empty($value)){
            $query->whereTime('add_time','>=',$value);
        }
    }
    public function searchAddTimeMaxAttr($query,$value,$data){
        if(!empty($value)){
            $query->whereTime('add_time','<=',$value);
        }
    }
    public function searchRecommendedAttr($query,$value,$data){
        if ("2"!==$value){
            $query->where('ecm_goods.recommended','=',$value);
        }
    }
    //复选框
    public function searchIfShowAttr($query,$value,$data)
    {
        if(is_array($value) && count($value)>0|| (is_scalar($value) &&  strpos('#'.$value,','))){
            $query->whereIn('ecm_goods.if_show',$value);
        }
        if(is_scalar($value) && false===strpos($value,',') && intval($value)<2){
            $query->where('ecm_goods.if_show',intval($value));
        }
    }

    //获取器
    public function getIfShowgAttr($value,$data){
        $ret = [0 => 'no.png',1=>'ok.png'];
        return $ret[$data['if_showg']];
    }
    public function getRecommendedAttr($value,$data){
        $ret = [0 => 'no.png',1=>'ok.png'];
        return $ret[$data['recommended']];
    }

    public function getAddTimeAttr($value,$data){
        return date('Y-m-d H:i:s',$value);
    }

    public static function getGoods($data=[],$query=[],$page=false,$sj=[])
    {


        $field = [
            'goods_id', 'goods_name', 'default_image','g.if_show'=>'if_showg','g.recommended',
            'parent_id', 'price', 'g.cate_name'=>'gcate_name', 'g.cate_id', 'add_time',
            "FROM_UNIXTIME(add_time,'%Y-%m-%d %H:%i:%S')" => 'add_date',

            'c.cate_name'=>'ccate_name', 'c.if_show'=>'if_showc',

            'b.brand_name'=>'bbrand_name',
];
        $model=self::alias('g')->field($field)
            ->join(['ecm_gcategory'=>'c'],'g.cate_id = c.cate_id','LEFT' )
            ->join(['ecm_brand'=>'b'],'b.brand_id=g.brand','LEFT')->withSearch(array_keys($data),$data);


        if($sj==1){
            View::assign('sj',2);
            $model->order('goods_id asc');
        }elseif ($sj==2){
            View::assign('sj',3);
            $model->order('g.add_time desc');
        }else{
            $model->order('g.add_time asc');
            View::assign('sj',1);
        }
        $list_rows = Config::has('view.list_rows')?Config::get('view.list_rows'):15;
        $urlPage=Request::get('page',1);
        $lastPage=$model->paginate(['list_rows'=>$list_rows,'query'=>$query])->toArray()['last_page'];
        if($urlPage > $lastPage){
            $urlPage = $lastPage;
        }

        if($page){
            $result=$model->select();
        }else{
            $result=$model->paginate([
                'list_rows' =>$list_rows,
                'fragment'=>'top',
                'query'=>$query,
                'page'=>$urlPage
            ])
                ->each(function ($item) use($data){
                if(!empty($data['keywords'])){
                    $item['goods_name']=
                        str_replace($data['keywords'],'<span style="color: red;font-weight: 900">'.$data['keywords'].'</span>',$item['goods_name']);
                    return $item;
                }
            });
        }

        return $result;


    }
    public function add(array $data, array $allowField = [], bool $replace = false) {

        try{
            if(empty($data)){
                $this->error = '新增数据不能为空！';
                return ;
            }
            // 限制写入的字段列表
            if (!empty($allowField))    $this->allowField($allowField);
            $this->replace($replace)->save($data);

            $goods_id=$this->goods_id;

           if(isset($data['image_url'])&& !empty($data['image_url'])){
               $insertData=[];
               foreach ($data['image_url'] as $v){
                   $thumb=$this->getThumb($v);
                   $insertData[]=['goods_id'=>$goods_id,'image_url'=>$v,'thumbnail'=>$thumb,'sort_order'=>1];

               }

               \think\facade\Db::table('ecm_goods_image')->insertAll($insertData);

           }



            return true;
        }catch (\Exception $e){
            $this->error = $e->getMessage();
            return false;
        }
    }

    public function getInsertId(){
        $data = $this->toArray();
        return $data[$this->pk];
    }
    //修改后加时间
    protected $autoWriteTimestamp = true;//
    protected $createTime = 'add_time';
    protected $updateTime = 'last_update';

    //修改后，新增后



//修改
    public function edit($data, $where = [], $allowField = []){

        try{
            if(empty($data)){
                $this->error = "修改数据不能为空!";
                return ;
            }

            if (!empty($allowField)) {
                $this->allowField($allowField);
            }

            if (!empty($where)) {
                $this->setUpdateWhere($where);
                if(isset($data[$this->pk]))     unset($data[$this->pk]);
            }

            return $this->exists(true)->save($data);

        }catch (\Exception $e){
            $this->error = $e->getMessage();
            return false;
        }
    }

    //删除
    public static function delgoods($id){
        self::startTrans();
        try{

            if(is_array($id) || (is_string($id) && false !== strpos($id,','))){
                //$id=implode(',',$id);

                $resultSet = self::onlyTrashed()->select($id);


                foreach($resultSet as $result){

                    $ret = $result->force(true)->delete();


                    if($ret === false){// 模型类事件能return false时来用的
                        self::rollback();
                        return false;
                    }else{
                       if(is_file('storage'.$result['default_image'])) {
                           unlink('storage'.$result['default_image']);
                       }

                    }
                }
                $image=GoodsImage::delimage($id);

                if($image === false){
                    self::rollback();
                    return false;
                }
                self::commit();
                return true;
            }


        }catch (\Exception $e){
            self::rollback();// 抛出异常方案用的
            return false;
        }
    }

    public function getThumb(string $path ='')
    {

        $thumbPath= str_replace('data/upload','up',$path);
//        $thumbPath= str_replace('up','data/upload',$path);
//        echo $thumbPath;
//        die;

        $arr = explode('/','storage/'.$path);
        $filename=$arr[count($arr)-1];
        unset($arr[count($arr)-1]);
        $Tmp_dir = implode('/',$arr);

        $tmb_dir=str_replace('data','new/data',$Tmp_dir);
        if(!is_dir($tmb_dir)) {
            mkdir($tmb_dir,777,true);
        }


       Image::open('storage/'.$thumbPath)->thumb(300,100,image::THUMB_FIXED)->save($tmb_dir.'/'.$filename);

        return $tmb_dir.'/'.$filename;

    }
    //
}

//$db= Db::table("ecm_goods")
//    ->alias('g')
//    ->field($field)
//    ->join(['ecm_gcategory'=>'c'],'g.cate_id = c.cate_id','LEFT' );
////名称模糊搜索
//if(""!==$goods_name){
//    $db->where('goods_name','like','%'.$goods_name.'%');
//}
//View::assign('goods_name',$goods_name);
////分类名称搜索
//if(""!==$cate_id){
//
//    $db->where(function ($q)use ($cate_id){
//        $q->where('c.cate_id','=',$cate_id);
//    });
//}
//View::assign('cate_id',$cate_id);
//
//if($price !==""){
//    $db->where('g.price','>=',$price);
//
//}
//View::assign('price',$price);
//
//if($price1 !==""){
//    $db->where('g.price','<=',$price1);
//}
//View::assign('price1',$price1);
//
//if($add_time !==""){
//    $db->whereTime('g.add_time','>=',$add_time);
//}
//View::assign('add_time',$add_time);
//
//if($add_time1 !==""){
//    $db->whereTime('g.add_time','<=',$add_time1);
//}
//View::assign('add_time1',$add_time1);
//if($recommended !=="2"){
//    $db->where('g.recommended','=',$recommended);
//}
//View::assign('recommended',$recommended);
//if(is_array($if_show) &&  1 == count($if_show) && 1 == $if_show[0]){
//    $db->whereIn('g.if_show',$if_show);
//}
//if(is_array($if_show) &&  1 == count($if_show) && 0 == $if_show[0]){
//    $db->where(function ($q) use ($if_show){
//        $q->whereIn('g.if_show',$if_show);
//    });
//}
//View::assign('if_show',$if_show);
//

//
//
//$sp=$db->paginate([
//    'list_rows'=>2,
//    'query'=>input('get.'),
//]);
//$page=$sp->render();